<template>
 <div>
  <div class="search">
    <input v-model="keywords" type="text" placeholder="输入城市或景点" class="search-content"/>
  </div>
  <div class="search-result" ref="result" v-show="keywords">
    <ul>
      <li class="search-text border-bottom" v-for="item of list" :key="item.id" @click="tabCity(item.name)">{{item.name}}</li>
      <li class="search-text border-bottom" v-show="hasnodata">
        没有找到匹配数据
      </li>
    </ul>
  </div>
 </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: ['cities'],
  data () {
    return {
      keywords: '',
      list: [],
      timer: null
    }
  },
  computed: {
    hasnodata () {
      return !this.list.length
    }
  },
  methods: {
    tabCity (city) {
      this.$store.commit('tabCity', city)
      this.$router.push('/')
    }
  },
  watch: {
    keywords () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keywords) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.name.indexOf(this.keywords) > -1 || value.spell.indexOf(this.keywords) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.result, {click: true})
  }
}
</script>

<style lang="stylus" scoped>
  .search
    height:.6rem
    padding: 0 .2rem
    background:#00afc7
    .search-content
      box-sizing:border-box
      width:100%
      height:.4rem
      text-align:center
      border-radius: .2rem
      margin-top:.1rem
      padding: 0 .1rem
  .search-result
    z-index:2
    position:absolute
    overflow:hidden
    top:1.58rem
    left:0
    right:0
    bottom:0
    background:#eee
    .search-text
      color:#666
      line-height:.5rem
      background:#fff
      padding-left:.2rem
    .border-bottom
      &:before
        border-color:#666
</style>
